<?php
/**
 * Created by PhpStorm.
 * User: lichuang
 * Date: 2022/9/21
 * Function: 逻辑层基类
 */

namespace app\logic;

use app\server\Log;
use app\server\Api;
use app\server\Aes;
use app\server\Auth;
use app\server\Server;
use app\server\Helper;

class BaseLogic
{
    static public $symbol = null;
    static public $req_time = null;

    public function __construct()
    {

    }

    // HTTP请求日志
    public function httpLog($method)
    {
        $info = array();
        // 请求方式
        $info['method'] = $method;
        // 请求时间
        list($s1, $s2) = explode(' ', microtime());
        $info['req_time'] = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
        self::$req_time = $info['req_time'];
        // 客户端ip
        $info['ip'] = Helper::getIp();
        // token
        $info['token'] = '';
        $info['userId'] = 0;
        $token = isset($_SERVER['HTTP_TOKEN']) ? $_SERVER['HTTP_TOKEN'] : '';
        if ($token != '') {
            $tokenEn = substr($token, 0, 8) . '**********' . substr($token, -8);
            $info['token'] = $tokenEn;
            // userId
            $aesInfoEn = substr($token, 30);
            $aesInfo = Aes::decode($aesInfoEn);
            if (!$aesInfo) {
                $userId = 0;
            } else {
                $aesInfo = explode("###", $aesInfo);
                $userId = $aesInfo[0];
            }
            $info['userId'] = $userId;
        }
        // 请求数据
        $httpData = file_get_contents('php://input');
        $info['req_data'] = $httpData;
        // 生成唯一标识
        $symbol = sha1(microtime(true) . uniqid(true) . mt_rand(10000000, 99999999));
        self::$symbol = $symbol;
        $info['symbol'] = $symbol;
        // 请求地址
        $info['route'] = Api::getRoute();
        // 记录请求日志
        $systemInfo = Server::getSystem();
        $coreInfo = isset($systemInfo['core']) ? $systemInfo['core'] : [];
        if ($coreInfo['api_log']) {
            Log::insertLog($info);
        }
    }

    // 签名验证
    public function checkSign()
    {
        $post = file_get_contents('php://input');
        $post = json_decode($post, true);
        $checkSign = Auth::checkSign($post);
        if (!$checkSign) {
            Api::error(1001);
        }
        // timestamp验证
        if (!isset($post['timestamp']) || ($post['timestamp'] + 600) < time()) {
            Api::error(1002);
        }
    }

    // TOKEN验证
    public function tokenCheck()
    {
        $token = isset($_SERVER['HTTP_TOKEN']) ? $_SERVER['HTTP_TOKEN'] : '';
        $tokenData = Auth::deToken($token);
        if (empty($tokenData)) {
            Api::error(1000);
        }
        return $tokenData;
    }
}